﻿using Assets.Scripts.Manager;
using Assets.Scripts.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using YeqianFramework;
using YeqianFramework.common;
using YeqianFramework.core;

namespace Assets.Scripts
{
	public class FKStartup : YQFKStartupMono
	{
		private LoadingSlider slider;
		public string NextSceneName;
		protected override void BuforeYQFKStartup()
		{
			slider = FindObjectOfType<LoadingSlider>();
		}

		protected override void OnLoadingContinue(float currentVal, float maxVal)
		{
			slider.SetValue(0.5f * currentVal / maxVal);//框架设置 为最多到进度条的 50%
		}

		protected override void AfterYQFKStartup()
		{
			TheThreeBodyGameManager.Current.onGlobalConfigLoadComplete += () =>
			{
				slider.SetValue(0.6f);//加载完全局配置，进度条跑到60%
				LoadScene();
				MessageCenter.Current.AddListener(UIEventType.LoadingSliderComplete, OnLoadingComplete);
			};
			TheThreeBodyGameManager.Current.LoadGameConfig();
		}

		AsyncOperation _ao;
		private void LoadScene()
		{
			StartCoroutine(LoadSceneAsync());
		}

		private IEnumerator LoadSceneAsync()
		{
			Debug.Log("开始加载场景");
			_ao = SceneManager.LoadSceneAsync(NextSceneName);
			_ao.allowSceneActivation = false;
			yield return new WaitWhile(()=> { return slider.isSliding; });

			slider.SetValue(1);
		}

		private void Update()
		{
			if (_ao != null)
			{
				float val = 0.6f + _ao.progress * 0.4f;
				if (val <= 0.85f)
					slider.SetValue(0.6f + _ao.progress * 0.4f);
				else
				{
					slider.SetValue(1);
				}
			}
		}

		private void OnLoadingComplete(KeyValuePair kv)
		{
			//slider.SetValue(1);
			_ao.allowSceneActivation = true;
			_ao.completed += ao => Debug.Log("场景加载完成！");
		}

		private void OnDestroy()
		{
			MessageCenter.Current.RemoveListener(UIEventType.LoadingSliderComplete, OnLoadingComplete);
		}
	}
}
